package com.zhihu.service.Impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.zhihu.client.AnswerClient;
import com.zhihu.client.QuestionClient;
import com.zhihu.pojo.Answer;
import com.zhihu.pojo.Question;
import com.zhihu.pojo.Type;
import com.zhihu.pojo.User;
import com.zhihu.pojo.baseVo.BaseResult;
import com.zhihu.pojo.req.AnswerReq;
import com.zhihu.pojo.req.HotQuestion;
import com.zhihu.pojo.req.QuestionReq;
import com.zhihu.service.IndexService;
import com.zhihu.utils.JwtUtils;
import com.zhihu.utils.RedisKeyUtils;
import com.zhihu.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    QuestionClient questionClient;

    @Autowired
    AnswerClient answerClient;

    @Override
    public BaseResult findIndexList(HttpServletRequest request) {
        //1.获取header中的token
        String token = request.getHeader("token");
        //2.调用方法，通过token获取用户感兴趣的问题
        List<QuestionReq> list = interestQuestion(token);
        //3.判断是否为空，为空说明未登录或未收藏
        if (list==null || list.isEmpty()){
            //调用接口，按时间排序获取所有问题
            BaseResult allQuestion = questionClient.findAllQuestion();
            List<QuestionReq> questions = JSONArray.parseArray(JSON.toJSONString(allQuestion.getData()), QuestionReq.class);
            return findAnsewr(questions);
        }
        return findAnsewr(list);
    }

    @Override
    public BaseResult findHotList() {
        Object o = redisUtils.get(RedisKeyUtils.MAP_HOT_QUESTION);
        List<HotQuestion> hotQuestions = JSONArray.parseArray(JSON.toJSONString(o), HotQuestion.class);
        if (hotQuestions.isEmpty()){
            return new BaseResult(0,"查询失败");
        }
        return new BaseResult(1,"查询成功",hotQuestions);
    }

    /**
     * 通过用户关注的问题获取可能感兴趣的问题
     * @param token 请求头中的token
     * @return    问题的集合
     */
    public List<QuestionReq> interestQuestion(String token){
        JwtUtils jwtUtils = new JwtUtils();
        if (token!=null && token != ""){
            //获取user
            String jwtToken = redisUtils.get(token).toString();
            String s = jwtUtils.VerifyToekn(jwtToken);
            //从json转为实体
            User user = JSONObject.parseObject(s, User.class);
            //调用接口，通过userid获取关注的问题列表
            BaseResult baseResult = questionClient.findFavorQuesByUserId(user.getUserId());
            List<QuestionReq> list = JSONArray.parseArray(JSON.toJSONString(baseResult.getData()), QuestionReq.class);
            //
            if (!list.isEmpty()){
                Set set = new HashSet<>();
                for (QuestionReq question:list
                ) {
                    List<Type> typesList = question.getTypesList();
                    set.add(typesList);
                }
                List<Type> types = new ArrayList<Type>(set);
                Set questionSet = new HashSet<>();
                if (!types.isEmpty()){
                    for (Type type : types) {
                        //调用接口，通过标签查询问题
                        BaseResult quesByTypeId = questionClient.findQuesByTypeId(type.getTypeId());
                        List<QuestionReq> questions = JSONArray.parseArray(JSON.toJSONString(quesByTypeId.getData()), QuestionReq.class);
                        //将问题放进set集合中
                        questionSet.add(questions);
                    }
                    List<QuestionReq> questions = new ArrayList<>(questionSet);
                    questions.removeAll(list);
                    return questions;
                }
            }
            return null;
        }
        return null;
    }

    /**
     * 通过问题获取高赞回答，返回回答实体
     * @param list 问题的集合
     * @return      返回到前端的回答实体
     */
    public BaseResult findAnsewr(List<QuestionReq> list){
        List<Answer> answerReqs = new ArrayList<>();
        for (QuestionReq question:
                list) {
            Integer questionId = question.getQuestionId();
            //通过问题id查询所有回答,获取高赞的第一个回复
            BaseResult baseResult = answerClient.findAnswersByQuestionId(questionId);
            List<Answer> answers = JSONArray.parseArray(JSON.toJSONString(baseResult.getData()), Answer.class);
            if (answers!=null && !answers.isEmpty()){
                Answer answer = answers.get(0);
                //获取到问题的第一个回答，放进set集合
                answerReqs.add(answer);
            }

        }
        return new BaseResult(0,"查询成功",answerReqs);
    }

    /**
     * 获取前50条热门问题，并存进rides数据库中
     * @return
     */
    @Override
    public void findHotQuestion(){
        //调用接口，获取所有问题
        BaseResult allQuestion = questionClient.findAllQuestion();
        List<QuestionReq> list = JSONArray.parseArray(JSON.toJSONString(allQuestion.getData()), QuestionReq.class);
        //声明热度值
        int heat = 0;
        //声明HotQuestion的容器
        List<HotQuestion> hotQuestions = new ArrayList<>();
        //遍历
        for (QuestionReq questionReq:list) {
            Integer questionId = questionReq.getQuestionId();
            //通过问题id查询所有回答
            BaseResult baseResult = answerClient.findAnswersByQuestionId(questionId);
            List<Answer> answers = JSONArray.parseArray(JSON.toJSONString(baseResult.getData()), Answer.class);
            //生成热度值
            heat = questionReq.getQuesCommNums() + questionReq.getQuesLikeNum() + (answers.size()*10);
            for (Answer answer : answers) {
                heat = heat + answer.getAnsCommNums();
                if (questionReq.getQuesImg().isEmpty() && !answer.getAnsImg().isEmpty()){
                    questionReq.setQuesImg(answer.getAnsImg());
                }
            }
            HotQuestion hotQuestion = new HotQuestion();
            BeanUtils.copyProperties(questionReq,hotQuestion);
            hotQuestions.add(hotQuestion);
        }
        //调用接口，按热度排序
        List<HotQuestion> hotQuestions1 = hotQuestionSort(hotQuestions);
        //存进rides中
        redisUtils.set(RedisKeyUtils.MAP_HOT_QUESTION,hotQuestions1);

    }

    /**
     * 冒泡排序
     * @param list      热门问题
     * @return          按热度排行的前五十个问题
     */
    public List<HotQuestion> hotQuestionSort(List<HotQuestion> list){
        if (list.isEmpty() || list.size()<2){
            return null;
        }
        for (int i = 0 ; i < list.size()-1 ; i++ ){
            HotQuestion hotQuestion = new HotQuestion();
            for (int x = i+1 ; i < list.size() ; i++){
                if (list.get(i).getHotAmount()<list.get(x).getHotAmount()){
                    hotQuestion = list.get(i);
                    list.set(i,list.get(x));
                    list.set(x,hotQuestion);
                }
            }
        }
        if (list.size()<50){
            return list;
        }
        return list.subList(0,50);
    }
}
